package com.ddl.task;

import com.ddl.common.enums.ResultType;
import com.ddl.dao.PayFlowMapper;
import com.ddl.pay.MchOrderInfoResult;
import com.ddl.pay.WeixinPay;
import com.ddl.pojo.PayFlow;
import com.ddl.pojo.PayFlowWithBLOBs;
import com.ddl.service.MoneyRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author dudianbo
 * @ClassName: ${CLASSNAME}
 * @Description: ${DESCRIPTION}
 * @date 2019/2/25
 */
@Component
public class PayFlowTask {
    private static Logger log = LoggerFactory.getLogger(PayFlowTask.class);
    @Autowired
    PayFlowMapper payFlowMapper;
    @Autowired
    WeixinPay weixinPay;
    @Autowired
    MoneyRecordService moneyRecordService;

    @Scheduled(fixedDelay = 600000)
    public void afterPropertiesSet() throws Exception {
        PayFlow record=new PayFlow();
        record.setDealStatus(ResultType.PROCESSING.getCode());
        List<PayFlowWithBLOBs> payFlowWithBLOBsList= payFlowMapper.selectByRecord(record);
        for(PayFlowWithBLOBs payFlowWithBLOBs:payFlowWithBLOBsList){
            MchOrderInfoResult mchOrderInfoResult=weixinPay.payOrderquery(payFlowWithBLOBs.getOrderId());
            if("SUCCESS".equals(mchOrderInfoResult.getTrade_state())){
                PayFlow update=new PayFlow();
                update.setOrderId(payFlowWithBLOBs.getOrderId());
                update.setDealStatus(ResultType.SUCCESS.getCode());
                payFlowMapper.updateByOrderId(update);
                BigDecimal gold=payFlowWithBLOBs.getAmount().movePointRight(2);
                moneyRecordService.proveder(Integer.parseInt(payFlowWithBLOBs.getUserId()), gold, "微信充值");
            }else if("FAIL".equals(mchOrderInfoResult.getTrade_state())){
                PayFlow update=new PayFlow();
                update.setOrderId(payFlowWithBLOBs.getOrderId());
                update.setDealStatus(ResultType.FAILED.getCode());
                payFlowMapper.updateByOrderId(update);
            }else if("NOTPAY".equals(mchOrderInfoResult.getTrade_state())){
                PayFlowWithBLOBs update=new PayFlowWithBLOBs();
                update.setId(payFlowWithBLOBs.getId());
                update.setDealStatus(ResultType.FAILED.getCode());
                update.setMessage(new String(mchOrderInfoResult.getTrade_state_desc().getBytes("iso8859-1"), "utf-8"));
                payFlowMapper.updateByPrimaryKeySelective(update);
            }
        }
    }

}
